package com.study.uploadcsv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.study.uploadcsv.model.EsDetectedData;
import com.study.uploadcsv.service.UploadCSVService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author weixiaochun
 * @date 2022/7/19 20:24
 */
@Service
public class UploadCSVServiceImpl implements UploadCSVService {
    /**
     * 导出csv文件
     *
     * @param response response
     */
    @Override
    public void upload(HttpServletResponse response) throws UnsupportedEncodingException {
        //附件下载
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(String.format("%s.csv",  System.currentTimeMillis() + ""), "UTF-8"));
        //获取响应输出流
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            StringBuffer buf = new StringBuffer();
            buf.append("站点编码,检测时间,站点编码,车道号,站点类型(0-固定治超站； 3-非现站；4-源头企业;5-移动治超),车牌号码,车牌颜色（0-蓝色；1-黄色；2-黑色；3-白色；4-渐变绿色；5- 黄绿双拼色；6-蓝白渐变色；9-未确定；11-绿色；12-红色）,接收时间,轴数,轴组数," +
                    "轴组型,车速（单位：km/h）,加速度（单位：m/s2）,车长（单位：mm）,车宽（单位：mm）,车高（单位：mm）,车货总重（单位：kg）,轴重1（单位：kg）,轴重2（单位：kg）,轴重3（单位：kg）,轴重4（单位：kg）,轴重5（单位：kg）,轴重6（单位：kg）,轴重7（单位：kg）," +
                    "轴重8（单位：kg）,轴1-2距（单位：mm）,轴2-3距（单位：mm）,轴3-4距（单位：mm）,轴4-5距（单位：mm）,轴5-6距（单位：mm）,轴6-7距（单位：mm）,轴7-8距（单位：mm）," +
                    "超限量（单位：kg）,超限标识（0、未超限；1、超限）,超限率（100*超限量/限重，保留2位小数）,限重,限长,限宽,限高,单双驱（0-单驱；1-双驱；默认0）,是否是黑名单（0-不是；1-是）," +
                    "是否Gps异常（0-不是；1-是）,是否是无牌车（0-不是；1-是）,是否是套牌车（0-不是；1-是）,是否遮挡车牌号（0-不是；1-是）,是否是大件运输车（0-不是；1-是）,大件运输许可证,客货标识（0-货车；1-客车。默认值为0）," +
                    "绿通车辆标识（0-否；1-是。默认值为0）,绿通车辆标识（0-否；1-是。默认值为0）,特种车辆标识（0-否；1-是。默认值为0）,复检标识（0-否；1-是。默认值为0）,车道方向（0-上行；1-下行）,超限类型（0：未超限，1：超重，2：超尺寸）," +
                    "初检业务号（当数据为初检时传空。为复检时关联初检业务号）,源头企业名称,公司名称,经营许可证,从业资格证书,货物类型,车主姓名,驾驶证号," +
                    "驾驶员姓名,道路运输许可证,复检员姓名,车辆许可证,插入ES的时间（格式：yyyy-MM-dd HH:mm:ss）,轴数标志,车辆类型,克隆车牌号,完整标识,车头照片,是否异常（0-否；1-是。默认值为0）," +
                    "大件运输许可证号,超限标识,车牌照片,车道类型,遮盖车牌号,短视频,站点名称,车尾图片,车辆品牌,车辆颜色,车牌标识,全景图片\n");

            FileInputStream inputStream = null;

            Scanner sc = null;
            StringBuilder sb = new StringBuilder();
            try {
                inputStream = new FileInputStream("D:\\study\\data\\temp-data\\result10.txt");
                sc = new Scanner(inputStream, "UTF-8");
                while (sc.hasNextLine()) {
                    sb.append(sc.nextLine());
                }
                if (sc.ioException() != null) {
                    throw sc.ioException();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (sc != null) {
                    sc.close();
                }
            }
            String s = sb.toString();
            Map map = JSON.parseObject(s, Map.class);
            Map hits = (Map) map.get("hits");
            JSONArray jsonArray = JSON.parseArray(hits.get("hits").toString());
            List<EsDetectedData> list = new ArrayList<>(100000);
            for (Object o : jsonArray) {
                Map parseObject = JSON.parseObject(o.toString(), Map.class);
                Object source = parseObject.get("_source");

                EsDetectedData esDetectedData = JSON.parseObject(source.toString(), EsDetectedData.class);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sdf.setTimeZone(TimeZone.getTimeZone("CST"));
                String format = sdf.format(esDetectedData.getDetectionTime());
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                Date newDate = sdf.parse(format);
                esDetectedData.setDetectionTime(newDate);
                buf.append(esDetectedData.toString()).append("\n");
            }

            os.write(0xef);
            os.write(0xbb);
            os.write(0xbf);
            os.write(buf.toString().getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            IOUtils.closeQuietly(os);
        }
    }

    @Override
    public String readFile(String path) throws IOException {
        FileInputStream inputStream = null;
        Scanner sc = null;
        StringBuilder sb = new StringBuilder();
        try {
            inputStream = new FileInputStream(path);
            sc = new Scanner(inputStream, "UTF-8");
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine());
            }
            if (sc.ioException() != null) {
                throw sc.ioException();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (sc != null) {
                sc.close();
            }
        }
        String s = sb.toString();
        Map map = JSON.parseObject(s, Map.class);
        Map hits = (Map) map.get("hits");
        JSONArray jsonArray = JSON.parseArray(hits.get("hits").toString());
        List<EsDetectedData> list = new ArrayList<>(100000);
        for (Object o : jsonArray) {
            Map parseObject = JSON.parseObject(o.toString(), Map.class);
            Object source = parseObject.get("_source");

            list.add(JSON.parseObject(source.toString(), EsDetectedData.class));
        }

        return list.get(1).toString();
    }
}
